package com.ze.familyday.familyphotoframesquare;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mouse.customview.CustomDialog;
import com.mouse.customview.CustomToast;
import com.mouse.customview.TasksCompletedView;
import com.mouse.remind.AlarmModel;
import com.mouse.remind.AlarmUpdateReceiver;
import com.mouse.remind.AlarmUpdateService;
import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.BaseDialog;
import com.ze.commontool.Constant;
import com.ze.commontool.LoadImageMgr;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.commontool.SoundPlayStop;
import com.ze.commontool.StringTools;
import com.ze.commontool.TemplateBitmapMrg;
import com.ze.commontool.ToastUtil;
import com.ze.commontool.LoadImageMgr.ImageCallBack;
import com.ze.commontool.SoundPlayer;
import com.ze.commontool.UpdateTools;
import com.ze.familyday.familyphotoframesquare.R;
import com.ze.familydayverpm.adapter.SpaceViewPagerAdapter;
import com.ze.familydayverpm.userinfo.Componet;
import com.ze.familydayverpm.userinfo.UserInfoManager;
import com.ze.model.DataModel;
import com.ze.model.ModelDataMgr;
import com.ze.model.PhotoModel;
import com.ze.model.PhotoModel.CommentInfo;
import com.ze.model.PhotoModel.PicInfo;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PhotoFrameActivity extends BaseActivity {
	
	public static final int MSG_CHECK_VERSION = 0;
	public static final int MSG_FIRST_CHECK = 999;
	public static final int MSG_RELOADING = 1;
	public static final int MSG_PUSH = 2;
	public static final int TEMPLATE_MSG = 516400;
	
	/**
	 * 2014.2.25
	 */
	//public static TasksCompletedView playSoundBtn;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	/**
	 * 滑动屏幕调节声音
	 */
	private RelativeLayout tipsRl;
	/**
	 * 音量级别UI
	 */
	public static RelativeLayout mLevelRl;
	public static TextView mLevelTv;
	private 	ViewPager 						mViewPager;
	private 	SpaceViewPagerAdapter 		mviewAdapter;
	
	
	AlertDialog 	mProgressDialog;
	//JSONArray array ;
	public static ArrayList<PhotoModel> mListData = null;
	
	private int currentPage = 0;
	public static PhotoFrameActivity mInstance;
	/**
	 * 菜单栏按钮，从左到右，最新、收藏夹、我的、收藏、退出
	 */
	private ImageButton mIbPlayRefresh, mIbPlayLove, mIbPlayMine, mIbLove, mIbExit;
	private TextView mTvPlayAll, mTvPlayLove, mTvPlayMine, mTvLove, mTvExit;
	
	private View menuView;
	/**
	 * 父控件
	 */
	private ImageView mPhotoFrameView;	// img 父控件
	// 整个界面的父控件
	private Animation menuInAnimation;
	private Animation menuOutAnimation;
	private int 				model = PLAYING_ALL;
	private boolean 	uselocal;
	boolean isLogin = true;
	private String 		m_auth;
	
	private RelativeLayout rlRoot;
	
	private   int  pageCount = 0;  // 计算当前数据包括了几页
	/**
	 * 连击5下进入debugmodel
	 */
	View 			checkButtonView;
	private Context mContext;
	
	/**
	 * 充电状态
	 */
	int currentLevel = -1;
	
	private boolean soundTipsRlFlag;
	
	private static boolean isTurnScreen = false;
	private Dialog mLoadingDialog;
	/**
	 * 字体文件
	 */
	Typeface typeface;
	private boolean needSwitchModel = false;
	/**
	 * 若没有更多图片了，则设置为true
	 */
	private boolean nomorepic = false;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		isTurnScreen = true;
		outState.putSerializable("mListData", mListData);
		outState.putInt("pageCount", pageCount);
		outState.putSerializable("arrayList", arrayList);
		outState.putInt("checkcount", checkcount);
		outState.putInt("currentPage", currentPage);
		outState.putBoolean("firstShowFlag", firstShowFlag);
		outState.putBoolean("initFlag", initFlag);
		outState.putBoolean("isDestryoed", isDestryod);
//		outState.putBoolean("isLoadingPic", isLoadingPic);
		outState.putInt("loadImgCount", loadImgCount);
		outState.putBoolean("loadListTaskFlag", loadListTaskFlag);
		outState.putString("uid", mUidString);
		outState.putBoolean("menuShowFlag", muneShowFlag);
		outState.putInt("model", model);
		outState.putBoolean("uselocal", uselocal);
		outState.putBoolean("isLogin", isLogin);
		outState.putBoolean("playstop", play_stop);
		outState.putBoolean("onsave", true);
		outState.putInt("indexArrayList", indexArrayList);
		outState.putInt("sizeOfList", sizeOfList);
		outState.putInt("c_sizeOfList", c_sizeOfList);
		
	}
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_frame);
		initView();
		// 清空缓存文件，如果此次更新与缓存文件无关，则可注释
		// 如有关，需要在函数下修改清空标志
		UpdateTools.installClear(this);
		ModelDataMgr.getInstance();
		mContext = this;
		mInstance = this;
		isTurnScreen = false;
		initAnimation();
		SharedPreferences soundPreferences = 
				getSharedPreferences("update.config", Activity.MODE_WORLD_READABLE);
		soundTipsRlFlag = soundPreferences.getBoolean("soundTipsRl", false);
		uselocal = getIntent().getBooleanExtra("uselocal",false);
 		if( uselocal )
 		{
 			m_auth = null;
 		}else
 		{
 			Componet componet = UserInfoManager.getInstance(this).getItem("m_auth");
 			if (componet != null) {
				m_auth = componet.getValue();
			}
 		}
		
		/*model = getIntent().getIntExtra("model", PLAYING_ALL);*/
		if( model == PLAYING_ALL )
		{
			//mIbPlayAll.setSelected(true);
		}else if (model == PLAYING_LOVE)
		{
			mIbPlayLove.setSelected(true);
		} else
		{
			mIbPlayMine.setSelected(true);
		}
		
		PublicInfo.SCREEN_W = getWindowManager().getDefaultDisplay().getWidth();
		PublicInfo.SCREEN_H = getWindowManager().getDefaultDisplay().getHeight();
		
		if ( this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE )
		{
			isLandscape = true;
		}else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			isLandscape = false;
		}
		
		if (savedInstanceState != null && savedInstanceState.getBoolean("onsave", false)) {
			changeScreenInit(savedInstanceState);
			mViewPager.setVisibility(View.INVISIBLE);
			mviewAdapter = new SpaceViewPagerAdapter(this, mListData);
			mViewPager.setAdapter(mviewAdapter);
			onpage(currentPage);
		}else
		{
			if (!uselocal){
				loadListTask(true, model);
				
			} else {
				getLocalListTask(model);
			}
		}
		
		
		// 锁定wifi不休眠
		 WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
         wifiLock = manager.createWifiLock("SwiFTP");
         wifiLock.setReferenceCounted(false);
         wifiLock.acquire();
         
         pm = (PowerManager)getSystemService(POWER_SERVICE); 
         mWakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
         wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
          
         // 网络线程
         networkThread = new HandlerThread("network");
         networkThread.start();
         networkHandler = new Handler(networkThread.getLooper());
         pushRunnableList = new ArrayList<Runnable>();
         
         //注册监测wifi广播 By mouse
         IntentFilter wififilter = new IntentFilter();
         wififilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         wififilter.addAction(Intent.ACTION_BATTERY_CHANGED);
         wififilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
         wififilter.addAction("WIFI_TO_PHOTO");
         wififilter.addAction(Constant.ACTION.SCAN_ACTIVITY_FINISH);
         wififilter.addAction(Constant.ACTION.TO_PHOTO_TO_SWITCH_MODEL);
         registerReceiver(mBroadcastReceiver, wififilter);
         
         initPlayHandle();
	}
	
	private void initView(){
		//TODO: initView()
		mViewPager = (ViewPager)findViewById(R.id.photoshowViewPager);
		initWidget(mViewPager);
		tipsRl = (RelativeLayout) findViewById(R.id.tipsRl);
		tipsRl.setOnTouchListener(touchlistener);
		mLevelRl = (RelativeLayout) findViewById(R.id.levelRl);
		mLevelTv = (TextView) findViewById(R.id.levelTv);
		mLevelRl.setVisibility(View.INVISIBLE);
		mPhotoFrameView = (ImageView)findViewById(R.id.pic_content_layout);
		mPhotoFrameView.setOnClickListener(buttonClickListener);
		//initWidget(mPhotoFrameView);
		/*playSoundBtn = (TasksCompletedView) findViewById(R.id.playSoundBtn);
		playSoundBtn.setOnClickListener(buttonClickListener);
		playSoundBtn.setSelected(false);
		playSoundBtn.setTag("stop");*/
		checkButtonView = findViewById(R.id.photoframe_check);
		checkButtonView.setOnClickListener(buttonClickListener);
		mIbPlayRefresh = (ImageButton) findViewById(R.id.ibPlayRefresh);
		mIbPlayRefresh.setOnClickListener(buttonClickListener);
		mTvPlayAll = (TextView) findViewById(R.id.tvPlayAll);
		mTvPlayAll.setOnClickListener(buttonClickListener);
		mIbExit = (ImageButton) findViewById(R.id.ibExit);
		mIbPlayLove = (ImageButton) findViewById(R.id.ibPlayLove);
		mIbPlayLove.setOnClickListener(buttonClickListener);
		mTvPlayLove = (TextView) findViewById(R.id.tvPlayLove);
		mTvPlayLove.setOnClickListener(buttonClickListener);
		mIbPlayMine = (ImageButton) findViewById(R.id.ibPlayMine);
		mIbPlayMine.setOnClickListener(buttonClickListener);
		mTvPlayMine = (TextView) findViewById(R.id.tvPlayMine);
		mTvPlayMine.setOnClickListener(buttonClickListener);
		mIbLove = (ImageButton) findViewById(R.id.ibLove);
		mIbLove.setOnClickListener(buttonClickListener);
		mTvLove = (TextView) findViewById(R.id.tvLove);
		mTvLove.setOnClickListener(buttonClickListener);
		mIbExit = (ImageButton) findViewById(R.id.ibExit);
		mIbExit.setOnClickListener(buttonClickListener);
		mTvExit = (TextView) findViewById(R.id.tvExit);
		mTvExit.setOnClickListener(buttonClickListener);
		menuView = findViewById(R.id.photoframe_menu_layout);
		mLoadingDialog = new CustomDialog.Builder(this)
		.setCustomButton(new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mLoadingDialog.dismiss();
			}
		})
		.create(1);
		mLoadingDialog.setCanceledOnTouchOutside(false);
		rlRoot = (RelativeLayout) findViewById(R.id.rlRoot);
		//typeface = Typeface.createFromAsset(getAssets(), "fonts/say.ttf");
		ScanActivity.hasStartScanAct = false;
	}
	
	/*public void setFonts(TextView tv) {
		tv.setTypeface(typeface);
	}*/
	//MyScroller mScroller;
	private void initWidget(View v) {
		if (v == mViewPager) {
			arrayList = new ArrayList<DataModel>();
			mListData = new ArrayList<PhotoModel>();
			mviewAdapter = new SpaceViewPagerAdapter(this, mListData);
			mViewPager.setAdapter(mviewAdapter);
			mViewPager.setOnClickListener(buttonClickListener);
			mViewPager.setOnPageChangeListener(pageChangeListener);
			/*try {
				Field mField = ViewPager.class.getDeclaredField("mScroller");
				mField.setAccessible(true);
				mScroller = new MyScroller(mViewPager.getContext(), new AccelerateInterpolator());  
	            mScroller.setmDuration(1000);
				mField.set(mViewPager, mScroller);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}else if (v == mPhotoFrameView) {//应用模板
			SharedPreferences sharedPreferences = getSharedPreferences("template", MODE_PRIVATE);
			Componet componet = UserInfoManager.getInstance(this).
					getItem("uid");
			if (componet == null) {
				return;
			}
			String tempalteUrl = sharedPreferences.getString(componet.getValue(), "default");
			PublicInfo.templateUrl = tempalteUrl;
			if (tempalteUrl.equals("default")) {
				mPhotoFrameView.setBackgroundDrawable(null);
			}else {
				Bitmap bm = TemplateBitmapMrg.getInstance().LoadBitmap(tempalteUrl);
				if (bm != null) {
					if (mPhotoFrameView.getTag() != null) {
						StringTools.rececleBm((Bitmap)mPhotoFrameView.getTag());
					}
					mPhotoFrameView.setTag(bm);
					mPhotoFrameView.setImageBitmap(bm);
					
				}else {
					mPhotoFrameView.setImageBitmap(null);
				}
			}
		}
	}
	private void initAnimation() {
		indexAnimation = new AlphaAnimation(0.0f, 1.0f);
		indexAnimation.setAnimationListener(animationListener);
		indexAnimation.setDuration(500);
		dismissAnimation = new AlphaAnimation(1.0f, 0.0f);
		dismissAnimation.setAnimationListener(animationListener);
		dismissAnimation.setDuration(500);
		menuInAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
				Animation.RELATIVE_TO_SELF, -1.0f, 
				Animation.RELATIVE_TO_SELF,0.0f);
		menuInAnimation.setAnimationListener(animationListener);
		menuInAnimation.setDuration(200);
		menuInAnimation.setFillEnabled(true);
		menuInAnimation.setFillAfter(true);
		menuOutAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
				Animation.RELATIVE_TO_SELF, 0.0f, 
				Animation.RELATIVE_TO_SELF,-1.0f);
		menuOutAnimation.setAnimationListener(animationListener);
		menuOutAnimation.setDuration(200);
		menuOutAnimation.setFillEnabled(true);
		menuOutAnimation.setFillAfter(true);
		commentAlphaAnimation = new AlphaAnimation(0, 1);
		commentAlphaAnimation.setDuration(500);
		commentAlphaAnimation.setFillAfter(true);
		commentTranAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
				Animation.RELATIVE_TO_SELF, 0.0f, 
				Animation.RELATIVE_TO_SELF,-1.0f);
		commentTranAnimation.setDuration(1500);
		commentTranAnimation.setFillAfter(true);
	}
	
	boolean testFlag = true;
	
	
	
	ArrayList<Runnable> pushRunnableList = null;
    HandlerThread networkThread;
    Handler networkHandler;
    PowerManager pm;
    WakeLock wl;
    WifiLock wifiLock;
//	 KeyguardLock keyguardLock = null;
    WakeLock mWakeLock = null;
    boolean isLandscape = true;
    
	@SuppressWarnings("unchecked")
	public void changeScreenInit(Bundle saveBundle)  
	{
		mListData = (ArrayList<PhotoModel>)saveBundle.getSerializable("mListData");
		pageCount = saveBundle.getInt("pageCount");
		arrayList = (ArrayList<DataModel>) saveBundle.getSerializable("arrayList");
		checkcount = saveBundle.getInt("checkcount");
		currentPage = saveBundle.getInt("currentPage");
		firstShowFlag	 = saveBundle.getBoolean("firstShowFlag");
		initFlag	 = saveBundle.getBoolean("initFlag");
		isDestryod	 = saveBundle.getBoolean("isDestryoed");
		loadImgCount = saveBundle.getInt("loadImgCount");
		loadListTaskFlag	 = saveBundle.getBoolean("loadListTaskFlag");
		mUidString	= saveBundle.getString("uid");
		muneShowFlag = saveBundle.getBoolean("menuShowFlag");
		play_stop = saveBundle.getBoolean("playstop");
		if( play_stop )
		{
			menuView.setVisibility(View.VISIBLE);
			menuView.startAnimation(menuInAnimation);
		}
		model = saveBundle.getInt("model");
		uselocal = saveBundle.getBoolean("uselocal");
		indexArrayList = saveBundle.getInt("indexArrayList");
		sizeOfList = saveBundle.getInt("sizeOfList");
		c_sizeOfList = saveBundle.getInt("c_sizeOfList");
	}
	/**
	 * 字体处理
	 */
	TextPaint newPaint_name, newPaint_time, newPaint_say, newPaint_saybody;
	/**
	 * 各字体View
	 */
	TextView new_name_back, new_name, new_time_back, new_time, new_say_back,
				new_say;
	
	ArrayList<DataModel> arrayList = null;
	boolean loadListTaskFlag = false;
	String mUidString = null;
	AsyncTask<String, String, String> taskLoadList = null;
	AsyncTask<String, String, String> taskLoveLoadList = null;
	
	boolean localhasShow = false;
	public void getLocalListTask(final int model){
		new AsyncTask<Object, Object, Object>(){

			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if (!localhasShow){
					if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
						mLoadingDialog.show();
					}
					localhasShow = true;
				}
				mListData.clear();
			}

			@Override
			protected Object doInBackground(Object... params) {
				switch (model) {
				case PLAYING_ALL:
					arrayList = ModelDataMgr.getInstance().getIdList(ModelDataMgr.PHOTO_ID_ALL_LIST);
					break;
				case PLAYING_LOVE:
					arrayList = ModelDataMgr.getInstance().getIdList(ModelDataMgr.PHOTO_ID_LOVE_LIST);
					break;
				case PLAYING_MINE:
					arrayList = ModelDataMgr.getInstance().getIdList(ModelDataMgr.PHOTO_ID_MINE_LIST);
					break;
				default:
					break;
				}
				if (arrayList == null)
					arrayList = new ArrayList<DataModel>();
				
				int length = 0;
				length = arrayList.size();
				int i = 0;
				int index = 0;
				while (i < length){
					DataModel model;
					model =  (DataModel) ModelDataMgr.getInstance().getModel(arrayList.get(index).id,ModelDataMgr.PHOTO_DIR);
					if (model == null) {
						arrayList.remove(index);
					}
					else {
						if (((PhotoModel)model).id.contains("defaultID")){
							index ++;
						} else {
							if (((PhotoModel)model).photos != null && ((PhotoModel)model).photos.size() >= 1) {
								String url = ((PhotoModel)model).photos.get(0).url;
								String imgUrl = url;
								File file = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance()
										.formatString(imgUrl));
								if (file.exists()){
									index ++;
								} else {
									arrayList.remove(index);
								}
							}
						}
					}
					i ++;
				}
				if (arrayList.size() == 0){
					// 无图情况下，播放默认
					// 初始化默认
					DataModel object;
					ModelDataMgr.getInstance().initDefaultPic();
					for (i = 0; i < 4; i++) {
						object = new DataModel();
						object.id = PublicInfo.picID_defaults[i];
						object.uid ="";
						object.type = "photoid" ;
						arrayList.add(object);
					}
					return null;
				}
				return null;
			}

			@Override
			protected void onPostExecute(Object result) {
				super.onPostExecute(result);
				if(  arrayList.size() > 0 && arrayList.size() > mListData.size() )
				{
					loadDetailTask(arrayList.get(indexArrayList ++));
				}
			}
			
			
		}.execute("");
		
	}
	
	public void loadListTask(final boolean refresh, final int loadModel){
		if (needSwitchModel) {
			needSwitchModel = false;
			loadListTask(true, model);
			return;
		}
		if( refresh )
		{
			mListData.clear();
			if( loadListTaskFlag )
			{
				return;
			}
				
		}
		taskLoadList = new AsyncTask<String, String, String>(){
			protected void onPreExecute() {
				if ( mUidString == null )
				{
					Componet uidComponet = UserInfoManager.getInstance(mContext).getItem("uid");
					if( uidComponet != null )
					{
						mUidString = uidComponet.getValue();
					}
				}
				if( refresh )
				{
					PublicInfo.netError = true;
					if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
						mLoadingDialog.show();
					}
					loadListTaskFlag = true;
					// 避免过久的等待，网络中断等问题
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							if(isDestryod)
							{
								return;
							}
							if (PublicInfo.netError) {
								System.err.println("Loading Failed!---loadListTask");
								if (mLoadingDialog.isShowing())
									mLoadingDialog.dismiss();
								taskLoadList.cancel(true);
								Dialog dialog = new CustomDialog.Builder(mContext).setMessage("网络好像不给力！请选择？")
										.setNegativeButton("返回登录", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												AlarmModel.cancel(mContext);
												Componet uidComponet = UserInfoManager.getInstance(mContext).getItem("uid");
												if (uidComponet != null) {
													FamilyDayVerPMApplication.unBindJpush(PhotoFrameActivity.this, uidComponet.getValue());
													Componet userComponet = UserInfoManager.getInstance(mContext).getItem("username");
													UserInfoManager.getInstance(mContext).deleteAll();
													if ( userComponet != null ) {
														UserInfoManager.getInstance(mContext).save(userComponet);
														UserInfoManager.getInstance(mContext).add(userComponet);
													}
													Intent intent = new Intent();
													intent.setClass(mContext, MainActivity.class);
													startActivity(intent);
													PhotoFrameActivity.this.finish();
//													unregisterReceiver(receiver);
												} else {
													Intent intent = new Intent();
													intent.setClass(mContext, MainActivity.class);
													startActivity(intent);
													PhotoFrameActivity.this.finish();
												}
											}
										})
										.setPositiveButton("重试", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
													mLoadingDialog.show();
												}
												NetHelper.resetWifi(mContext);
												executorService.submit(new Runnable() {
													
													@SuppressWarnings("static-access")
													@Override
													public void run() {
														int count = 0;
														ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
														NetworkInfo.State state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
														while (state != NetworkInfo.State.CONNECTED && count < 30) {
															count ++;
															try {
																Thread.sleep(1000);
															} catch (InterruptedException e) {
																e.printStackTrace();
															}
															state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
														}
														handler.sendEmptyMessage(MSG_RELOADING);
													}
												});
												
											}
										}).create(0);
								dialog.setCanceledOnTouchOutside(false);
								dialog.show();
							}
						}
					}, PublicInfo.MAX_TIME_WAITLAOD);
				}
			};
			
			@Override
			protected String doInBackground(String... params) {
				String page = "1";
				if( !refresh )
				{
					pageCount ++ ;
					page = pageCount + "";
				}
				if( refresh )
				{
					
					pageCount = 1;
					page = pageCount + "";
				}
				String responString ;
				if ( null == m_auth ) {
					 return "";
				}
				getFmembers();
				String httpStr;
				if (loadModel == PLAYING_ALL) {
					httpStr = getResources().getString(R.string.http_subscribe_feedlist/*增加订阅号http_feedlist*/);
					responString = NetHelper.getResponByHttpClient(httpStr,
							"photoid",page,m_auth);
					if (refresh) {
						String str = getResources().getString(R.string.http_regilist/*增加订阅号http_feedlist*/);
						firtPhotoList = NetHelper.getResponByHttpClient(str,
								"photoid",page,m_auth);
					}
				} else if (loadModel == PLAYING_LOVE) {
					httpStr = getResources().getString(R.string.http_lovelist);
					responString= NetHelper.getResponByHttpClient(httpStr,
							m_auth,page);
				} else {
					httpStr = getResources().getString(R.string.http_minelist);
					responString = NetHelper.getResponByHttpClient(httpStr,
							"photoid",page,m_auth);
				}
				
				if( refresh && responString != null && !responString.equals("") )
				{
					ModelDataMgr.getInstance().savePhotoListResponse(responString,1);//本地保存该列表
				}
				return responString;
			}
			protected void onPostExecute(String result) {
				loadListTaskFlag = false;
				if( result != null && !result.equals("") )
				{
					if( refresh  )
					{
						model = loadModel;
						currentPage = 0;
						arrayList.clear();
						indexArrayList = 0;
						update(result, refresh);
						return;
					}else
					{
						update(result, refresh);
					}
				}else {
					CustomToast.show(mContext, R.string.invalid_network);
					mLoadingDialog.dismiss();
				}
			};
		}.execute("");
	}
	
	private String firtPhotoList;
	
	public void setTimerRefresh()
	{
		checkVersion(executorService, MSG_FIRST_CHECK, handler);
		new Thread(new Runnable() {
				
				@Override
				public void run() {
					int count = 0;
					while(count < PublicInfo.REFRESH_TIME)
					{
						if (isDestryod) {
							return;
						}else
						{
							try {
								Thread.sleep(1000);
								count++;
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					//时间到
					if( mListData != null ){
						try {
							// 当前是否处于推送暂停状态
							while( play_stop && mListData.get(currentPage).pushnoread)
							{
								Thread.sleep(1000);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					// 开始调用刷新任务
					handler.sendEmptyMessage(MSG_CHECK_VERSION);
				}
			}).start();
	}
	
	public void switchModel(int pModel)
	{
		Intent intent = new Intent();
		intent.setClass(PhotoFrameActivity.this, PhotoFrameActivity.class);
		intent.putExtra("model", pModel);
		intent.putExtra("uselocal", uselocal);
		intent.putExtra("refreshComment", true);
		PhotoFrameActivity.this.startActivity(intent);
		PhotoFrameActivity.this.finish();
		isDestryod = true;
	}
	int indexArrayList = 0;
	
	private int mCount = 0;
	private void update(String result, boolean refresh)
	{
		try {
			if (refresh && firtPhotoList != null) {
				JSONObject onlyPhotoObject = new JSONObject(firtPhotoList);
				if (0 == onlyPhotoObject.getInt("error")) {
					JSONArray tempArray = onlyPhotoObject.getJSONArray("data");
					DataModel object ;
					if (tempArray.length() == 0) {
						ModelDataMgr.getInstance().initDefaultPic();
						for (int i = 0; i < 4; i++) {
							object = new DataModel();
							object.id = PublicInfo.picID_defaults[i];
							object.uid ="";
							object.type = "photoid" ;
							arrayList.add(object);
						}
						firtPhotoList = "nophoto";
					}
				}
			}
			JSONObject jsonObject = new JSONObject(result);
			if ( 0 == jsonObject.getInt("error") )
			{
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				int size = jsonArray.length();
				JSONObject temp;
				DataModel object ;
				if ( size == 0 && mListData.size() == 0 && mCount == 0 && firtPhotoList == null)
				{
					// 无图情况下，播放默认
					// 初始化默认
					ModelDataMgr.getInstance().initDefaultPic();
					for (int i = 0; i < 4; i++) {
						object = new DataModel();
						object.id = PublicInfo.picID_defaults[i];
						object.uid ="";
						object.type = "photoid" ;
						arrayList.add(object);
					}
					firtPhotoList = "nophoto";
				}else
				{
					for (int i = 0; i < size; i++) {
						temp = jsonArray.getJSONObject(i);
						object = new DataModel();
						object.id = temp.getString("id");
						object.uid = temp.getString("uid");
						object.type = temp.getString("idtype");
						if (object.type.equals("blogid")) {
							if (!subscribeMap.containsKey(object.uid)) {
								subscribeMap.put(object.uid, object.id);
								mCount ++;
								arrayList.add(object);
							}
						}else {
							mCount ++;
							arrayList.add(object);
						}
					}
					/*if (size == 15 && mCount < 8) {
						loadListTask(false, model);
						return;
					}
					mCount = 0;
					c_sizeOfList = arrayList.size();*/
				}
			}
			
			if( arrayList.size() > 0 && arrayList.size() > indexArrayList  )
			{
				loadDetailTask(arrayList.get(indexArrayList ++));
				switch (model) {
				case PLAYING_ALL:
					ModelDataMgr.getInstance().saveIdList(arrayList,ModelDataMgr.PHOTO_ID_ALL_LIST );
					break;
				case PLAYING_LOVE:
					ModelDataMgr.getInstance().saveIdList(arrayList,ModelDataMgr.PHOTO_ID_LOVE_LIST );
					break;
				case PLAYING_MINE:
					ModelDataMgr.getInstance().saveIdList(arrayList,ModelDataMgr.PHOTO_ID_MINE_LIST );
					break;
				default:
					break;
				}
			}else
			{
				if (arrayList.size() > 0 && indexArrayList == arrayList.size()) {
					CustomToast.show(mContext, "没有更多图片");
					nomorepic = true;
				}
				if (mLoadingDialog.isShowing())
					mLoadingDialog.dismiss();
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
			if (mLoadingDialog.isShowing())
				mLoadingDialog.dismiss();
		}
	}
	
	HashMap<String , String> subscribeMap = new HashMap<String, String>();
	
	public void loadDetailTask(final DataModel picJsonObject)
	{
		if (needSwitchModel) {
			needSwitchModel = false;
			loadListTask(true, model);
			return;
		}
		if( isDestryod )
		{
			return;
		}
		
		new AsyncTask<String, String, PhotoModel>(){
			
			boolean notopen = false;
			private boolean error = false;			// 读取操作中是否出错
			String typeidString = "photoid";
			String dirPath = null;
			String urlString = null;
			String commentUrl = "";
			
			protected void onPreExecute() {
				typeidString = picJsonObject.type;
				if ( typeidString.equals("photoid") || typeidString.equals("rephotoid")) {
					dirPath = ModelDataMgr.PHOTO_DIR;
					urlString = getResources().getString(R.string.http_photo_detail);
					commentUrl = getResources().getString(R.string.http_photo_disscuss_audio);
				}else if (typeidString.equals("blogid")) {
					dirPath = ModelDataMgr.BLOG_DIR;
					urlString = getResources().getString(R.string.http_blog_detail);
					commentUrl = getResources().getString(R.string.http_blog_disscuss);
				}
			};
			@Override
			protected PhotoModel doInBackground(String... params) {
				if (isDestryod) {
					return null;
				}
				if( notopen )
				{
					return null;
				}
				PhotoModel model = null;
				try {
					model =  (PhotoModel) ModelDataMgr.getInstance().getModel(picJsonObject.id,dirPath);
				if (uselocal){
					return model;
				}else {
					if (model != null) {
						loadComments(commentUrl, model);
					}
				}
				//如果是播放默认的时候执行的是model!= null
				boolean loadPicFlag = true;
				if ( model == null && m_auth != null ) {
					String respon = NetHelper.getResponByHttpClient(urlString,
							picJsonObject.id,
							picJsonObject.uid,
							m_auth);
					JSONObject object = new JSONObject(respon);
					if ( 0 == object.getInt("error") ) {
//						model = new DataModel();
						object = object.getJSONObject("data");
						
						if ( typeidString.equals("photoid") || typeidString.equals("rephotoid")
								|| typeidString.equals("blogid") || typeidString.equals("reblogid")) {
							model = new PhotoModel();
							model.id 			= picJsonObject.id;
							model.uid 		= picJsonObject.uid;
							model.type		= picJsonObject.type;
							if( !object.isNull("name") )
							{
								((PhotoModel)model).name 	=  object.getString("name");
							}
							if( !object.isNull("dateline") )
							{
								((PhotoModel)model).time 	=  object.getString("dateline");
							}
							if( !object.isNull("tagname") )
							{
								((PhotoModel)model).tagname 	=  object.getString("tagname");
								
							}
							if (!object.isNull("subject")) {
								((PhotoModel)model).subject = object.getString("subject");
							}else {
								((PhotoModel)model).subject = "";
							}
							if (!object.isNull("soundtime")) {
								((PhotoModel)model).soundtime = object.getString("soundtime");
							}else {
								((PhotoModel)model).soundtime = "";
							}
							if (!object.isNull("pic")) {
								if (typeidString.equals("blogid") || typeidString.equals("reblogid")) {
									String picString = object.getString("pic");
									if (picString != null && picString.length() >= 1) {
										picString = "h" + picString.substring(1);
										String [] temp = picString.split("!");
										if (temp != null && temp.length == 2) {
											picString = temp[0] + "!512";
										}
										((PhotoModel)model).pic = picString;
										File drawableFile = new File(LoadImageMgr.PIC_CACHE_PATH + 
												LoadImageMgr.getInstance().formatString( picString ) );
										if ( ! drawableFile.exists()) {
											PicInfo picInfo = new PicInfo();
											picInfo.url = picString;
											picInfo.width = 512;
											picInfo.height = 768;
											LoadImageMgr.getInstance().loadImageFromUrl(picInfo);
										}
									}
								}
							}else {
								((PhotoModel)model).pic = "";
							}
							if( !object.isNull("message") )
							{
								String messageString = object.getString("message");
								if (typeidString.equals("blogid") || typeidString.equals("reblogid")) {
									if (model.uid.equals("26")) {
										((PhotoModel)model).message = messageString;
									}else {
										((PhotoModel)model).message = PublicInfo.webViewPadding 
												+ messageString.replaceAll("<img.*(jpg|png|gif)(![0-9]{3}(X[0-9]{3})*)*\">", "");
									}
									((PhotoModel)model).say = "";
								}else {
									((PhotoModel)model).message 	=  "";
									((PhotoModel)model).say = messageString;
								}
							}else {
								((PhotoModel)model).message = "";
								((PhotoModel)model).say = "";
							}
							if( !object.isNull("subject") )
							{
								((PhotoModel)model).tagname 		=  object.getString("subject");
							}
							if( !object.isNull("mylove") )
							{
								((PhotoModel)model).love 		=  object.getInt("mylove");
							}
							//语音相关字段
							if ( !object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
								((PhotoModel)model).soundurl = object.getString("soundurl");
								try {
									((PhotoModel)model).soundFileName = ModelDataMgr.getInstance().downFile(((PhotoModel)model).soundurl, "");
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							
//							多图情况处理
							if( ! object.isNull("piclist"))
							{
								JSONArray picArray = object.getJSONArray("piclist");
								if( picArray == null || picArray.length() == 0 )
								{
									return null;
								}
								PicInfo picInfo;
								for (int i = 0; i < picArray.length(); i++) {
									if (isDestryod) {
										break;
									}
									if (i == 9)
										break;
									picInfo = new PicInfo();
									picInfo.url = picArray.getJSONObject(i).getString("pic");
									picInfo.height = Integer.parseInt( picArray.getJSONObject(i).getString("height") );
									picInfo.width 	=  Integer.parseInt( picArray.getJSONObject(i).getString("width") );
										
									/**
									 * 这里加入url后缀处理 
									 * By mouse 2013.10.30PM
									 */
									String imgUrl = picInfo.url;
									int endFlag = -1;
					          		endFlag = imgUrl.indexOf("!");
					          		if ( endFlag != -1 || imgUrl.contains(PublicInfo.picID_default_head) )
					          		{
					          			if( ! imgUrl.contains(PublicInfo.picID_default_head))
					          			{
					          				imgUrl = imgUrl.substring(0, endFlag);
					          				imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
					          			}
										
					          		}
									picInfo.url = imgUrl;
									((PhotoModel)model).photos.add(picInfo
											);
									File drawableFile = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance().formatString( picInfo.url ) );
									if ( ! drawableFile.exists()) {
										loadPicFlag = LoadImageMgr.getInstance().loadImageFromUrl(picInfo);
									}
										
								}
							}
						}//end ..if ( typeidString.equals("photoid")..
						//loadComments(commentUrl, model);
						if (loadPicFlag) {
							ModelDataMgr.getInstance().saveModel(model,dirPath);
							System.out.println("网络加载的model！--- " + indexArrayList);
						}else {
							System.out.println("网络加载的model失败！--- " + indexArrayList);
							error = true;
						}
					}else
					{
						// 找不到该id的数据或者获取这个数据时出错了，得到的id得不到详情的内容 
						error = true;
					}
					
				}else {
					System.out.println("缓存的model！---" + indexArrayList);
				}
				// 得到model
				} catch (JSONException e) {
					e.printStackTrace();
					if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
						mLoadingDialog.dismiss();
					}
				}
				return model;
			}
			protected void onPostExecute(PhotoModel result) {
				if (isDestryod) {
					return;
				}
				if( notopen )
				{
					return;
				}
				if ( ! error ) {
					if( result == null )
					{
						arrayList.remove(picJsonObject);
					}else
					{
						try {
							
							int n = result.photos.size();
							//处理照片帖子
							for (int i = 0; i < n; i++) {
								PhotoModel object = new PhotoModel();
								ArrayList<PhotoModel.PicInfo> photo = new ArrayList<PhotoModel.PicInfo>();
								photo.add(result.photos.get(i));
								object.id = result.id;
								object.type = typeidString;
								object.fromUid = result.fromUid;
								object.fromName = result.fromName;
								object.love = result.love;
								object.uid = result.uid;
								if( typeidString.equals("photoid") || typeidString.equals("rephotoid"))
								{
									object.photos = photo;
									if (result.say.equals("")) {
										object.say = "我家幸福时光";
									}else {
										object.say = result.say;
									}
									object.time = result.time;
									if (fmembersList.containsKey(result.uid) && !fmembersList.get(result.uid).equals("")) {
										object.name = fmembersList.get(result.uid);
									}else {
										object.name = result.name;
									}
									object.tagname = result.tagname;
									object.tagid = result.tagid;
									//语音相关字段
									object.soundurl = result.soundurl;
									object.soundFileName = result.soundFileName;
									object.soundtime = result.soundtime;
								}
								object.pic = result.pic;
								object.comments = result.comments;
								if (initFlag) {
									tempList.add(object);
								}else {
									mListData.add(object);
								}
								//mListData.add(object);
								/*if (initFlag) {
									mviewAdapter.notifyDataSetChanged();
									if (ScanActivity.hasStartScanAct) {
										Intent intent = new Intent("to_scan_to_loadmorepic");
										sendBroadcast(intent);
									}
								}*/
							}
							if (n == 0 && (typeidString.equals("blogid") || typeidString.equals("reblogid"))) {
								PhotoModel object = new PhotoModel();
								ArrayList<PhotoModel.PicInfo> photo = new ArrayList<PhotoModel.PicInfo>();
								object.id = result.id;
								object.type = typeidString;
								object.fromUid = result.fromUid;
								object.fromName = result.fromName;
								object.love = result.love;
								object.uid = result.uid;
								object.photos = photo;
								object.say = result.subject;
								object.time = result.time;
								object.message = result.message;
								if (fmembersList.containsKey(result.uid) && !fmembersList.get(result.uid).equals("")) {
									object.name = fmembersList.get(result.uid);
								}else {
									object.name = result.name;
								}
								object.tagname = result.tagname;
								object.tagid = result.tagid;
//								//语音相关字段
								object.soundurl = result.soundurl;
								object.soundFileName = result.soundFileName;
								object.soundtime = result.soundtime;
								object.pic = result.pic;
								object.comments = result.comments;
								//mListData.add(object);
								if (initFlag) {
									tempList.add(object);
								}else {
									mListData.add(object);
								}
								mListPushJSON.add(object);
								/*if (initFlag) {
									mviewAdapter.notifyDataSetChanged();
									if (ScanActivity.hasStartScanAct) {
										Intent intent = new Intent("to_scan_to_loadmorepic");
										sendBroadcast(intent);
									}
								}*/
								
							}
							
							if( currentPage == 0 && !initFlag )
							{
								if ( (indexArrayList < arrayList.size() && mListData.size() > 4)
										|| (indexArrayList == arrayList.size() && mListData.size() > 4)
										|| (indexArrayList == arrayList.size()) ) 
								{
									if (mLoadingDialog != null && mLoadingDialog.isShowing()){
										PublicInfo.netError = false;
										mLoadingDialog.dismiss();
									}
									initFlag = true;
									resetPlayHandler();
									mviewAdapter.notifyDataSetChanged();
									if (firtPhotoList != null && firtPhotoList.equals("nophoto")) {
										new CustomDialog.Builder(mContext).setMessage("请您浏览使用帮助，让您快捷了解操作步骤！")
										.setPositiveButton("关闭", null).create(0).show();
										firtPhotoList = "";
									}
									if (!uselocal) {
										setTimerRefresh();
									}
									startPullService(true);
									ctrlService(true);
									Log.v("test", "********** start to show! ***********");
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				}else {
					PhotoModel object = new PhotoModel();
					try {
						object.id = "-1";
						object.type = "(((";
						object.say = getResources().getString( R.string.notexist );
					} catch (Exception e) {
						e.printStackTrace();
						mLoadingDialog.dismiss();
					}
					/*mListData.add(object);
					if (initFlag) {
						mviewAdapter.notifyDataSetChanged();
						if (ScanActivity.hasStartScanAct) {
							Intent intent = new Intent("to_scan_to_loadmorepic");
							sendBroadcast(intent);
						}
					}*/
					if (initFlag) {
						tempList.add(object);
					}else {
						mListData.add(object);
					}
					//mviewAdapter.notifyDataSetChanged();
				}
				if (initFlag) {
					PublicInfo.netError = false;
				}
				if (indexArrayList < arrayList.size()) {
					loadDetailTask(arrayList.get(indexArrayList ++));
				}else {
					if (tempList.size() > 0) {
						mListData.addAll(tempList);
						mviewAdapter.notifyDataSetChanged();
						tempList.clear();
						if (ScanActivity.hasStartScanAct) {
							Intent intent = new Intent("to_scan_to_loadmorepic");
							sendBroadcast(intent);
						}
					}
					loadListTask(false, model);
				}
				
			}
		}.execute("");
	}
	
	ArrayList<PhotoModel> tempList = new ArrayList<PhotoModel>();
	
	private 	HandlerThread 	playThread;
	private 	Handler 		playHandler;
	ArrayList<Runnable> 		playRunnableList = null;
	private 	PlayRunnble 		playRun = null;
	public void initPlayHandle()
	{
		 // 
		playThread = new HandlerThread("play");
		playThread.start();
		playHandler = new Handler(playThread.getLooper());
		playRunnableList = new ArrayList<Runnable>();
	}
	public class PlayRunnble implements Runnable{
		int count;
		public boolean out;
		@Override
		public void run() {
			while( !out && count < PHOTO_SHOW_COUNT )
			{
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				count++;
			}
			// 无操作时间结束 开始进入播放模式
			if( !out )
				handler.sendEmptyMessage(99);
		}
	}
	public void resetPlayHandler()
	{
		if( mListData == null || mListData.size() == 0 || mListData.size() == 1)
		 {
			// 只有一张或者0不自动播放
			 return;
		 }
		removePlayThread();
		
		playRun = new PlayRunnble();
		playHandler.post(playRun);
	}
	public void removePlayThread()
	{
		if( playRun != null ){
			playRun.out = true;
			playHandler.removeCallbacks(playRun);
		}
	}
	public static final String SIZEMODEL_1 = "320";
	public static final String SIZEMODEL_2 = "512X768";
	
	int loadImgCount = 0;
	public boolean isLoadingPic = false;
	boolean firstShowFlag = false;	
	boolean hasAddFlag = false;
	boolean treamFlag = false;
	
	
	public static List<Bitmap> recycleBm = new ArrayList<Bitmap>();
	public boolean isDestryod = false;
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
		if (!isTurnScreen) {
			isDestryod = true;
		}
		for( int i = 0; i< pushRunnableList.size(); i++ )
		{
			if( pushRunnableList.get(i) != null )
			{
				networkHandler.removeCallbacks(pushRunnableList.get(i));
			}
			Log.v("test", "清除线程！");
		}
		pushRunnableList.clear();
		
		if( wifiLock != null && wifiLock.isHeld() )
		{
			wifiLock.release();
		}
		if(mWakeLock != null && mWakeLock.isHeld() )
		{
			mWakeLock.release();
		}
		testFlag = false;
		//销毁mediaplayer
		SoundPlayStop.getInstance().deStroySound();
		if (mPhotoFrameView.getTag() != null) {
			StringTools.rececleBm((Bitmap)mPhotoFrameView.getTag());
		}
		try {
			
			for (int i = 0; i < recycleBm.size(); i++) {
				Bitmap bitmap = recycleBm.get(i);
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
				}
			}
			
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		if (mWifiDialog != null) {
			mWifiDialog.dismiss();
		}
		if (mLoadingDialog != null) {
			mLoadingDialog.dismiss();
		}
		
		
	}
	private boolean muneShowFlag = false;
	public AnimationListener animationListener = new AnimationListener() {
		
		@Override
		public void onAnimationStart(Animation animation) {
			if ( animation == dismissAnimation  ) {
//				setPicInfo(null);
			}else if( animation == indexAnimation )
			{
				try {
					mViewPager.setVisibility(View.VISIBLE);
				} catch (Exception e) {
				}
			}
			animation_playing = true;
		}
		
		@Override
		public void onAnimationRepeat(Animation animation) {
			
		}
		
		@Override
		public void onAnimationEnd(Animation animation) {
			animation_playing = false;
			if( animation == menuOutAnimation )
			{
				menuView.setVisibility(View.INVISIBLE);
				mIbLove.setSelected(false);
				return;
			}else if( animation == menuInAnimation )
			{
				initLoveStatus();
				menuView.setVisibility(View.VISIBLE);
				return;
			}
			 if (animation == dismissAnimation ) {
				 mViewPager.setVisibility(View.INVISIBLE);
				 int toIndex = currentPage;
				 if (toIndex + 1 >= mListData.size() ) {
				 // @ mouse
				 if ( mListPushJSON.size() > 0) {
					 for (int i = 0; i < mListPushJSON.size(); i++) {
						mListData.remove(mListData.lastIndexOf(mListPushJSON.get(i)));	
					}
					 mviewAdapter.notifyDataSetChanged(1);
					 mListPushJSON = new ArrayList<PhotoModel>();
				}
				 
				toIndex = 0;
				 }else {
					toIndex ++;
				}
				 if (toIndex < mListData.size()) {
					 mViewPager.setCurrentItem(toIndex, false);
					 onpage(toIndex);
				}
			 }else if( animation == indexAnimation )
			{
			 	ifPushData();
				resetPlayHandler();
			}
		}
	};
	public void onpage(int arg0)
	{
		try {
			currentPage = arg0;
			if( mViewPager.getVisibility() == View.INVISIBLE && indexAnimation != null )
			{
				mViewPager.startAnimation(indexAnimation);
			}
			if(  arg0 >= mListData.size() || mListData.get(arg0) == null )
			{
				arg0 = 0;
			}
			initLoveStatus();
			mUidString = mListData.get(arg0).uid;
			if (mViewPager.getVisibility() == View.VISIBLE) {
				ifPushData();
			}
			/*if( arrayList.size() > 5 && sizeOfList < c_sizeOfList
					&& mListData.get(arg0).id.equals(arrayList.get(arrayList.size() - 5).id)  )
			{
				sizeOfList = c_sizeOfList;
				loadListTask(false,model);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	int sizeOfList = 0;
	int c_sizeOfList = 0;
	/**
	 * 是否需要唤醒屏幕
	 */
	public void ifAcque() {
		if (taskFlag){
			new AsyncTask<Object, Object, Object>(){

				@Override
				protected Object doInBackground(Object... params) {
					int timeCount = 0;
					while (!pm.isScreenOn() || timeCount >= 10){
						taskFlag = false;
						PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 						WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|
 								PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
 						wl.acquire(PublicInfo.ACQUIRE_MAX_TIME);
 						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
 						timeCount ++;
					}
					taskFlag = true;
					
					return null;
				}
				
			}.execute("");
		}
	}
	/**
	 * 判断是否是推送数据
	 */
	public void ifPushData() {
		try {
			if ( mListData!= null && mListData.size()-1 > currentPage && mListData.get(currentPage).pushnoread )
			{
				mListData.get(currentPage).pushnoread = false;
				// 播放声音
				AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				am.setStreamVolume(AudioManager.STREAM_MUSIC, 
						15, AudioManager.FLAG_ALLOW_RINGER_MODES);
				SoundPlayer.play(PhotoFrameActivity.this, R.raw.complete);
				stopOrContinue(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void initLoveStatus()
	{
		try {
			if ( mListData != null && mListData.size() > currentPage ) {
				int set = mListData.get(currentPage).love;
				if( set == 1 || model == PLAYING_LOVE ){
					mIbLove.setSelected(true);
				}else
				{
					mIbLove.setSelected(false);
				}
			}
	} catch (Exception e) {
		e.printStackTrace();
	}
	}
	public boolean play_stop = false;
	private boolean animation_playing = false;
	private boolean initFlag = false;
	public void stopOrContinue(boolean needStop)
	{
		if(  needStop )
		{
			//mScroller.setmDuration(200);
			play_stop = true;
				
			if (!muneShowFlag) {
				muneShowFlag = true;
				menuView.setVisibility(View.VISIBLE);
				menuView.startAnimation(menuInAnimation);
				// 2013.11.3
				mPhotoFrameView.setVisibility(View.GONE);
			}
		}else
		{
			//mScroller.setmDuration(1000);
			play_stop = false;
			if (muneShowFlag) {
				muneShowFlag = false;
				menuView.setVisibility(View.INVISIBLE);
				menuView.startAnimation(menuOutAnimation);
				// 2013.11.3
				mPhotoFrameView.setVisibility(View.VISIBLE);
			}
		}
	}
	private static int PHOTO_SHOW_TIME = 5000;
	private static int PHOTO_SHOW_COUNT = 5;
	
	
	private Handler handler = new Handler()
	{
		@SuppressWarnings("static-access")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_PUSH:
				PhotoModel model = (PhotoModel)msg.obj;
				int pos = mViewPager.getCurrentItem() + 1;
				mListData.add(pos, model);
				mListData.add(0, model);
				mListPushJSON.add(model);
				mviewAdapter.notifyDataSetChanged(pos);
				if (play_stop && menuView.getVisibility() == View.VISIBLE) {
					int index = mListData.lastIndexOf(model);
					mViewPager.setCurrentItem(index, false);
					onpage(index);
				}
				break;
			case MSG_CHECK_VERSION:
				// 定时检查新版本，没新版本则刷新
				checkVersion(executorService, 10086, handler);
				break;
			case MSG_FIRST_CHECK :
				try {
					String cur_version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
					if ( ! cur_version .equals(msg.obj)) {
						CustomToast.show(mContext, R.string.new_version);
						download();
					}
				} catch (NameNotFoundException e) {
					e.printStackTrace();
				}
				break;
			case 10086:
				checkUpdate(msg);
				break;
			case 8080:
				
				break;
			case 8081:
				break;
			case 99:
				// 进入播放模式
				if( menuView.getVisibility() == View.VISIBLE )
				{
					resetPlayHandler();
				}else
				{
					mViewPager.startAnimation(dismissAnimation);
				}
				
				break;
			
			case TEMPLATE_MSG:
				SharedPreferences sharedPreferences = getSharedPreferences("template", MODE_PRIVATE);
				Editor editor = sharedPreferences.edit();
				Componet componet = UserInfoManager.getInstance(mContext).getItem("uid");
				if (componet != null) {
					editor.putString(componet.getValue(), PublicInfo.templateUrl);
					editor.commit();
				}
				Bitmap bm = (Bitmap)msg.obj;
				if (bm != null) {
					if (mPhotoFrameView.getTag() != null) {
						StringTools.rececleBm((Bitmap)mPhotoFrameView.getTag());
					}
					mPhotoFrameView.setTag(bm);
					mPhotoFrameView.setImageBitmap(bm);
				}else {
					mPhotoFrameView.setImageBitmap(null);
				}
				
				break;
			case MSG_RELOADING:
				ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo.State state = conMan.getNetworkInfo(conMan.TYPE_WIFI).getState();
				if (state == NetworkInfo.State.CONNECTED){
					switchModel(PLAYING_ALL);
				}else {
					if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
						mLoadingDialog.dismiss();
					}
					CustomToast.show(mContext, "重连失败了，请稍候再试！");
				}
				break;
			default:
				break;
			}
		};
	};
	public void checkUpdate(Message msg)
	{
		try {
			String cur_version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			if ( ! cur_version .equals(msg.obj)) {
				CustomToast.show(mContext, R.string.new_version);
				download();
			}else {
				// 没有新版本
				if( model == PLAYING_ALL )
					switchModel(PLAYING_ALL);
				else
					switchModel(PLAYING_LOVE);
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	private Animation indexAnimation;
	private Animation dismissAnimation;
	
	public static final int CHANGE_TO_ALL = 1;
	public static final int CHANGE_TO_LOVE = 2;
	public static final int PLAYING_ALL = 22;
	public static final int PLAYING_LOVE = 11;
	public static final int PLAYING_MINE = 33;
	
	public void playsound() {
		if (!soundTipsRlFlag) {
			soundTipsRlFlag = true;
			SharedPreferences soundPreferences = 
					getSharedPreferences("update.config", Activity.MODE_WORLD_READABLE);
			Editor editor = soundPreferences.edit();
			editor.putBoolean("soundTipsRl", true);
			editor.commit();
			tipsRl.setVisibility(View.VISIBLE);
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					if (tipsRl.getVisibility() == View.VISIBLE) {
						tipsRl.setVisibility(View.GONE);
					}
				}
			}, 3000);
		}
	}
	
	/**
	 * 
	 */
	public OnClickListener buttonClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			if( v == mPhotoFrameView )
			{
				MobclickAgent.onEvent(mContext, "ScreenClick");
				stopOrContinue(!play_stop);
			}
			else if( v == mIbLove || v == mTvLove)
			{
				MobclickAgent.onEvent(mContext, "love");
				if (uselocal){
					showLocalDialog();
				}
				else{
					try {
						if (mListData != null && mListData.size() > currentPage ) {
							PhotoModel object = mListData.get(currentPage);
							
							if (!object.loveBtn) {
								object.loveBtn = true;
								requestSetLove(object);
							} else {
								
							}
							
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}else if( v == mIbPlayRefresh || v == mTvPlayAll)
			{
				MobclickAgent.onEvent(mContext, "refresh");
				switchModel(model);
			}else if( v == mIbPlayLove || v == mTvPlayLove)
			{
				MobclickAgent.onEvent(mContext, "see_collect");
				switchModel(PLAYING_LOVE);
			}else if(v == mIbPlayMine || v == mTvPlayMine)
			{
				//openWifiLogin();
				switchModel(PLAYING_MINE);
				
				/*final String [] items = getResources().getStringArray(R.array.jazzy_effects);
				new AlertDialog.Builder(mContext).setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						TransitionEffect effect = TransitionEffect.valueOf(items[which]);
						mViewPager.setTransitionEffect(effect);
					}
				}).show();*/
			}else if( v == mIbExit || v == mTvExit)
			{
				if (uselocal){
					showLocalDialog();
				} else {
					MobclickAgent.onEvent(mContext, "exit");
					Dialog dialog = new CustomDialog.Builder(mContext).setMessage("是否要退出账号？")
					.setNegativeButton("", null)
					.setPositiveButton("", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//退出登录，取消用户闹钟
							AlarmModel.cancel(mContext);
							
							Componet uidComponet = UserInfoManager.getInstance(mContext).getItem("uid");
							if (uidComponet != null) {
								FamilyDayVerPMApplication.unBindJpush(PhotoFrameActivity.this, uidComponet.getValue());
								Componet userComponet = UserInfoManager.getInstance(mContext).getItem("username");
								UserInfoManager.getInstance(PhotoFrameActivity.this).deleteAll();
								if ( userComponet != null ) {
									UserInfoManager.getInstance(mContext).save(userComponet);
									UserInfoManager.getInstance(mContext).add(userComponet);
									UserInfoManager.getInstance(mContext).save(uidComponet);
									UserInfoManager.getInstance(mContext).add(uidComponet);
								}
								Intent intent = new Intent();
								intent.setClass(mContext, MainActivity.class);
								startActivity(intent);
								PhotoFrameActivity.this.finish();
//								unregisterReceiver(receiver);
							} else {
								Intent intent = new Intent();
								intent.setClass(mContext, MainActivity.class);
								startActivity(intent);
								PhotoFrameActivity.this.finish();
							}
						}
					}).create(3);
					dialog.setCanceledOnTouchOutside(false);
					dialog.show();
				}
				
			}else if( v == checkButtonView )
			{
				checkcount++;
				if (checkcount == 5) {
					debug();
					checkcount = 0;
				}
			}else if (v == FD_leftBtn) {
				familyDialog.dismiss();
				NetHelper.treatRequest((String)FD_nameTv.getTag(), 1, mContext);
			}else if (v == FD_rightBtn) {
				familyDialog.dismiss();
				NetHelper.treatRequest((String)FD_nameTv.getTag(), 0, mContext);
			} 
				
		}
	};
	int INOROUT_FLAG = -1;
	
	private EditText debugEditText;
	public void debug()
	{
		debugEditText = new EditText(this);
		Dialog dialog = new AlertDialog.Builder(this).setView(debugEditText).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@SuppressWarnings("static-access")
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String str_debug = debugEditText.getText().toString();
				Intent intent = null;
				if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_TIME))
				{
					intent= new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_SOUND) )
				{
					intent= new Intent(android.provider.Settings.ACTION_SOUND_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_WIFI) )
				{
					intent= new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_SETTING) )
				{
					intent= new Intent(android.provider.Settings.ACTION_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_VERSION) )
				{
					checkVersion(executorService, 10086, handler);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_VERCOD) )
				{
					ToastUtil.show(PhotoFrameActivity.this, updateTools.GetVersion(PhotoFrameActivity.this));
				}
					
			}
		}).setTitle("Welcome to DebugModel !").create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}
	
	public void deletePlayingPhoto()
	{
		// 删除当前照片：动画->移除->取消暂停状态
		if ( animation_playing ) {
			return;
		}else
		{
			try {
				mListData.get(currentPage).delete = true;
				if (model == PLAYING_LOVE)
					//img_1.startAnimation(deleteOutAnimation);
				if(muneShowFlag && model == PLAYING_LOVE)
				{
					stopOrContinue(false);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	int checkcount = 0;
	/**
	 * 收藏操作！
	 * @param object
	 */
	public void requestSetLove(final PhotoModel object) {
		if (m_auth == null) {
			return;
		}
		
		if (mIbLove.isSelected()) {
			deletePlayingPhoto();
		}
		mIbLove.setSelected(!mIbLove.isSelected());
		executorService.submit(new Runnable() {
			
			@Override
			public void run() {
				try {
					String argType = "photoid";
					if (object.type.equals("rephotoid")) {
						argType = "photoid";
					} else if (object.type.equals("reblogid")) {
						argType = "blogid";
					} else {
						argType = object.type;
					}
					int loveState = object.love;
					if (loveState == 1) {
						loveState = 0;
					}else {
						loveState = 1;
					}
					String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_set_love), 
							object.id, 
							argType, 
							"" + loveState,m_auth);
					if (respon != null && !respon.equals("")) {
						JSONObject responObject = new JSONObject(respon);
						if( responObject.getInt("error") == 0 )
						{
							if (responObject.getString("msgkey").equals("add_feedlove_seccuss")
									|| responObject.getString("msgkey").equals("del_feedlove_seccuss")) {
								String dirname = "";
								if (object.type.equals("photoid")
										|| object.type.equals("rephotoid")) {
									dirname  = ModelDataMgr.PHOTO_DIR;
								}else if (object.type.equals("blogid")
										|| object.type.equals("reblogid")) {
									dirname  = ModelDataMgr.BLOG_DIR;
								}
								String idString  = object.type;
								DataModel currentDataModel = (DataModel) ModelDataMgr.getInstance().getModel(idString, dirname);
								if (currentDataModel != null) {
									if (responObject.getString("msgkey").equals("del_feedlove_seccuss")) {
										currentDataModel.love = 0;
									}else {
										currentDataModel.love = 1;
									}
									//currentDataModel.love = (love.isSelected() ? 1 : 0 );
									ModelDataMgr.getInstance().saveModel(currentDataModel, dirname);
									//mListData.get(currentPage).put("love", currentDataModel.love );
									//object.put("love", currentDataModel.love);
									object.love = currentDataModel.love;
								}
							}else {
								
							}
							
						}
					}
					//object.put("loveBtn", false);
					object.loveBtn = false;
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		});
	}
	
	public ImageCallBack imageCallBack = new ImageCallBack() {
		
		@Override
		public void setImage(Bitmap bitmap, String url, final ImageView view) {
			if( /*mActiveImages.contains(view) &&*/ url.equals((String)view.getTag()))
			{
				
				view.setImageBitmap(bitmap);
				
				//view.setImageBitmap(bitmap);
				if( isLoadingPic )
				{
					//view.startAnimation(indexAnimation);
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							if(isDestryod)
							{
								return;
							}
							if( view.getDrawable() != null)
								isLoadingPic = false;
						}
					}, PHOTO_SHOW_TIME);
				}
			}
		}
	};
	
	private Dialog mWifiDialog;
	public void notifyWifiChange()
	{
		if( uselocal )
		{
			return;
		}
		// 网络断开
		if( NetHelper.isNetAble(mContext) )
		{
			if (mWifiDialog != null && mWifiDialog.isShowing()) {
				mWifiDialog.dismiss();
			}
			if (uselocal) {
				uselocal = false;
				switchModel(model);
			}
		}else
		{
			if (mWifiDialog == null) {
				mWifiDialog = new CustomDialog.Builder(mContext).setMessage("网络断开了，请选择？")
						.setNegativeButton("离线使用", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								uselocal = true;
								Intent localIntent = new Intent(PhotoFrameActivity.this, PhotoFrameActivity.class);
								localIntent.putExtra("uselocal", true);
								startActivity(localIntent);
								PhotoFrameActivity.this.finish();
							}
						})
						.setPositiveButton("重设网络", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								openWifiLogin();
							}
						})
						.create(0);
				mWifiDialog.setCanceledOnTouchOutside(false);
			}
			if (!mWifiDialog.isShowing()) {
				mWifiDialog.show();
			}
		}
	}
	public void logErrorImgInfo(int index)
	{
//		array.getJSONObject(index);
	}
	public void openWifiLogin()
	{
		Intent intent = new Intent();
		intent.putExtra("fromPlay", true);
		intent.setClass(PhotoFrameActivity.this, WifiLoginActivity.class);
		startActivity(intent);
	}
		
	/**
	 * wifi信号的监听 
	 * By mouse
	 */
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		
		Dialog batteryDialog;
		CustomDialog.Builder builder;
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
				//notifyWifiChange();
			}else if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
				int type = intent.getIntExtra("plugged", -1);
				MainActivity.lastPlugged = MainActivity.currentPlugged;
				MainActivity.currentPlugged = type;
				if (MainActivity.lastPlugged != MainActivity.currentPlugged)
					MainActivity.isFirstFull = false;
				int level = intent.getIntExtra("level", -1);
				int scale = intent.getIntExtra("scale", -1);
				if (level >= 0 && scale > 0)
					currentLevel = (level * 100) / scale;
				if (builder == null) {
					builder = new CustomDialog.Builder(mContext);
					builder.setPositiveButton("确定", null);
				}
				if (batteryDialog != null && batteryDialog.isShowing())
					batteryDialog.dismiss();
				
				if (type == 1 && currentLevel >= 100 && !MainActivity.isFirstFull){
					MainActivity.isFirstFull = true;
					builder.setMessage("充电已完成");
					batteryDialog = builder.create(0);
					batteryDialog.show();
				} else if (type == 1 && MainActivity.lastPlugged != MainActivity.currentPlugged) {
					builder.setMessage("正在充电！当前电量：" + currentLevel + "%");
					batteryDialog = builder.create(0);
					batteryDialog.show();
				}
			}else if (intent.getAction().equals("WIFI_TO_PHOTO")) {
				switchModel(PLAYING_ALL);
			}else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
				if (State.CONNECTED == state) {
					if (uselocal) {
						uselocal = false;
						switchModel(model);
					}
				}else {
					notifyWifiChange();
				}
			}else if (intent.getAction().equals(Constant.ACTION.SCAN_ACTIVITY_FINISH)) {
				mLoadingDialog.dismiss();
				rlRoot.clearAnimation();
				int index = intent.getIntExtra("index", 0);
				model = intent.getIntExtra("play_model", PLAYING_ALL);
				if (index < mListData.size()) {
					mViewPager.setCurrentItem(index, false);
				}
				startPullService(true);
				ctrlService(true);
			}else if (intent.getAction().equals(Constant.ACTION.TO_PHOTO_TO_SWITCH_MODEL)) {
				//TODO:rece
				model = intent.getIntExtra("model", PLAYING_ALL);
				if (nomorepic) {
					nomorepic = false;
					loadListTask(true, model);
				}else {
					needSwitchModel = true;
				}
			}
		}
	};
	
	boolean taskFlag = true;
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
	}
	
	int posJsonArray = 0;
	int temp_pos = 0;
	/**
	 * By mouse
	 * 拉取到新数据的处理
	 * @author mouse 2013.10.24修复 推送顺序问题
	 */
	//boolean isPushing = false;
	JSONArray pushArray = new JSONArray();
	public void notifyPull(final JSONArray jsonArray){
		MobclickAgent.onEvent(mContext, "rec_pic");//收到推送
		new AsyncTask<Object, Object, PhotoModel>(){
			
			@Override
			protected PhotoModel doInBackground(Object... params) {
				try {
					JSONObject extraObject = jsonArray.getJSONObject(posJsonArray ++);
				    final String pushType 	= extraObject.optString("idtype");
				    final String uid				= extraObject.optString("uid");
				    final String id					= extraObject.optString("id");
				    
				    PhotoModel photoModel = null;
					if( m_auth == null )
						return null;
					String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_photo_detail),
							id,
							uid,
							m_auth);
					JSONObject object;
					try {
						object = new JSONObject(respon);
					if ( 0 == object.getInt("error") ) {
							object = object.getJSONObject("data");
							if( ! object.isNull("piclist")){
								JSONArray picArray = object.getJSONArray("piclist");
								PicInfo picInfo;
								for (int i = 0; i <picArray.length(); i++) {	// 相框暂时支持多图时9张图片
									if (i >= 9)
										break;
									photoModel = new PhotoModel();
									picInfo = new PicInfo();
									picInfo.url = picArray.getJSONObject(i).getString("pic");
									picInfo.height = Integer.parseInt( picArray.getJSONObject(i).getString("height") );
									picInfo.width 	=  Integer.parseInt( picArray.getJSONObject(i).getString("width") );
									
									String imgUrl = picInfo.url;
									int endFlag = -1;
					          		int img_w = picInfo.width;
					          		int img_h  = picInfo.height;
					          		endFlag = imgUrl.indexOf("!");
					          		if ( endFlag != -1 || imgUrl.contains(PublicInfo.picID_default_head) )
					          		{
					          			if( ! imgUrl.contains(PublicInfo.picID_default_head))
					          			{
					          				imgUrl = imgUrl.substring(0, endFlag);
											if( (double)img_h / (double)img_w < 10f/9f )
											{
												//imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
											}else
											{
												imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_HALF;
											}
					          			}
										
					          		}
									picInfo.url = imgUrl;
									photoModel.photos.add(picInfo
											);
									File drawableFile = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance().formatString( picInfo.url ) );
									if ( ! drawableFile.exists()) {
										LoadImageMgr.getInstance().loadImageFromUrl(picInfo);
									}
									photoModel.id 			= id;
									photoModel.uid 		= uid;
									photoModel.type		= pushType;
									if( !object.isNull("name") )
									{
										String nameString = object.getString("name");
										if (nameString == null || nameString.equals("")) {
											photoModel.name = "我家幸福时光";
										}else {
											photoModel.name 	=  nameString;
										}
									}
									if( !object.isNull("dateline") )
									{
										photoModel.time 	=  object.getString("dateline");
									}
									if( !object.isNull("message") )
									{
										photoModel.say 	=  object.getString("message");
									}
									if( !object.isNull("subject") )
									{
										photoModel.tagname 		=  object.getString("subject");
									}
									if( !object.isNull("mylove") )
									{
										photoModel.love 		=  object.getInt("mylove");
									}
									//增加声音保存的字段
									if ( !object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
										photoModel.soundurl = object.getString("soundurl");
										try {
											photoModel.soundFileName = ModelDataMgr.getInstance().downFile(photoModel.soundurl, "");
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
									if (!object.isNull("soundtime")) {
										photoModel.soundtime = object.getString("soundtime");
									}else {
										photoModel.soundtime = "";
									}
									photoModel.pushnoread = true;
									Message msg = new Message();
									msg.obj = photoModel;
									msg.what = MSG_PUSH;
									handler.sendMessage(msg);
								}
							}
								
						}
						//ModelDataMgr.getInstance().saveModel(photoModel,ModelDataMgr.PHOTO_DIR);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					return photoModel;
				
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				return null;
			}
			
			@Override
			protected void onPostExecute(PhotoModel result) {
				super.onPostExecute(result);
				if (posJsonArray < jsonArray.length()) {
					notifyPull(jsonArray);
				}
				else{
					posJsonArray = 0;
				}
			}
			
		}.execute("");
	}
	List<PhotoModel> mListPushJSON = new ArrayList<PhotoModel>();
	boolean isPalyPushPic = false;
	int posPushArray = 0;
	
	
	/**
	 * 启动服务 下载提醒当天提醒列表
	 */
	public void ctrlService(boolean flag){
		if (!flag) {
			Intent i = new Intent(mContext, AlarmUpdateService.class);
	    	mContext.stopService(i);
	    	return;
		}
		Intent i = new Intent(mContext, AlarmUpdateService.class);
    	mContext.startService(i); 
    	SharedPreferences preferences = getSharedPreferences("setting.config", MODE_PRIVATE);
    	Editor editor = preferences.edit();
    	if (preferences.getBoolean("AlarmUpdateReceiver", true)) {
    		Intent rIntent = new Intent(mContext, AlarmUpdateReceiver.class);
        	sendBroadcast(rIntent, null);
        	editor.putBoolean("AlarmUpdateReceiver", false);
        	editor.commit();
		}
    	
	}
	
	
	
	public void startPullService(boolean flag) {
		if (!flag) {
			Intent stopIntent = new Intent(mContext, PullImageService.class);
			mContext.stopService(stopIntent);
			return;
		}
		if( m_auth != null && !uselocal)
			{
				m_auth = UserInfoManager.getInstance(this).getItem("m_auth").getValue();
				//By mouse 
				//此处传入m_auth的值  并且启动服务
				PullImageService.m_auth = m_auth;
				Intent stopIntent = new Intent(mContext, PullImageService.class);
				mContext.stopService(stopIntent);
				Intent startIntent = new Intent(mContext, PullImageService.class);
				mContext.startService(startIntent);
				Log.v(PullImageService.TAG, "启动服务");
				
			}
	}
	
	/**
	 * 下载应用模板
	 * 
	 */
	public void useTemplate(final String pic) {
		if (pic.equals("defalut")) {
			Message msg = new Message();
			msg.what = TEMPLATE_MSG;
			msg.obj = null;
			handler.sendMessage(msg);
			return;
		}
		executorService.submit(new Runnable() {
			
			@Override
			public void run() {
				Bitmap bm = TemplateBitmapMrg.getInstance().LoadBitmap(pic);
				Message msg = new Message();
				msg.what = TEMPLATE_MSG;
				msg.obj = bm;
				handler.sendMessage(msg);
			}
		});
	}
	
	HashMap<String, String> fmembersList = new HashMap<String, String>();
	/**
	 * 获取家人列表信息
	 */
	public void getFmembers(){
		String fmembersStr = NetHelper.getResponByHttpClient(getResources().
				getString(R.string.http_fmemberslist), m_auth);
		try {
			JSONObject fmembersJson = new JSONObject(fmembersStr);
			if (fmembersJson.getInt("error") == 0) {
				fmembersJson = fmembersJson.getJSONObject("data");
				fmembersList.put(fmembersJson.getString("uid"), fmembersJson.getString("name"));
				JSONArray array = fmembersJson.getJSONArray("fmemberlist");
				for (int i = 0; i < array.length(); i++) {
					fmembersList.put(array.getJSONObject(i).getString("uid"), 
							array.getJSONObject(i).getString("name"));
					
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	Dialog familyDialog;
	Button FD_leftBtn;
	Button FD_rightBtn;
	TextView FD_nameTv;
	TextView FD_phoneTv;
	ImageView FD_headIv;
	/**
	 * 处理家人申请信息
	 */
	public void showFamilyDialog(JSONObject object){
		if (familyDialog == null) {
			familyDialog = new BaseDialog(mContext, 410, 320, R.layout.dialog_request_family,
					R.style.FullHeightDialog);
			familyDialog.setCanceledOnTouchOutside(false);
			View view = getLayoutInflater().inflate(R.layout.dialog_request_family, null);
			FD_leftBtn = (Button) view.findViewById(R.id.drf_cancel);
			FD_leftBtn.setText("同 意");
			FD_leftBtn.setOnClickListener(buttonClickListener);
			FD_rightBtn = (Button) view.findViewById(R.id.drf_OK);
			FD_rightBtn.setText("忽 略");
			FD_rightBtn.setOnClickListener(buttonClickListener);
			FD_nameTv = (TextView) view.findViewById(R.id.drf_name);
			FD_phoneTv = (TextView) view.findViewById(R.id.drf_phone);
			FD_headIv = (ImageView) view.findViewById(R.id.drf_head);
			familyDialog.setContentView(view);
		}
		try {
			String url = object.getString("avatar").replace("small", "middle");
			PicInfo picInfo = new PicInfo();
			picInfo.url = url;
			picInfo.width = 1024;
			picInfo.height = 768;
			FD_headIv.setImageBitmap(LoadImageMgr.getInstance().loadDrawble(
				picInfo, FD_headIv, LoadImageMgr.getInstance().imageCallBack));
			FD_phoneTv.setText(object.getString("phone"));
			FD_nameTv.setText(object.getString("name"));
			FD_nameTv.setTag(object.getString("uid"));
			familyDialog.show();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static int mCurrentProgress = 0;
	/**
	 * 显示圆形进度条
	 * @param time：播放时长
	 */
	/*public void showCircleBar(final double time) {
		
		executorService.submit(new Runnable() {
			private int mTotalProgress = 100;
			
			@Override
			public void run() {
				//playSoundBtn.setTag("run");
				mCurrentProgress = 0;
				while (mCurrentProgress < mTotalProgress) {//mTotalProgress = 100
					mCurrentProgress += 1;
					playSoundBtn.setProgress(mCurrentProgress);
					try {
						Thread.sleep((long)time);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				playSoundBtn.setTag("stop");
				
			}
		});
	}*/
	
	private OnTouchListener touchlistener = new OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (tipsRl.getVisibility() == View.VISIBLE) {
				tipsRl.setVisibility(View.GONE);
			}
			return false;
		}
	};
	
	Animation commentAlphaAnimation, commentTranAnimation;
	private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
		
		
		@Override
		public void onPageSelected(final int arg0) {
			
			onpage(arg0);
			if (mCurrentProgress != 100) {
				mCurrentProgress = 100;
			}
			SoundPlayStop.getInstance().stop();
			if (mLevelRl.getVisibility() == View.VISIBLE) {
				mLevelRl.setVisibility(View.INVISIBLE);
			}
		}
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			
		}
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
			
		}
	};
	
	private void showLocalDialog() {
		new CustomDialog.Builder(mContext).setMessage("请登录，再继续操作！")
		.setNegativeButton("继续浏览", null)
		.setPositiveButton("返回登录", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(PhotoFrameActivity.this, MainActivity.class);
				startActivity(intent);
				PhotoFrameActivity.this.finish();
			}
		}).create(0).show();
	}
	
	
	private void loadComments(String commentUrl, PhotoModel model) {
		try {
			String commentResponse = NetHelper.getResponByHttpClient(commentUrl, model.id, m_auth, "1");
			JSONObject cJsonObject = new JSONObject(commentResponse);
			if (!cJsonObject.isNull("error") && cJsonObject.getInt("error") == 0) {
				JSONArray cArray = cJsonObject.getJSONArray("data");
				ArrayList<CommentInfo> comments = new ArrayList<CommentInfo>();
				for (int j = 0; j < cArray.length(); j++) {
					cJsonObject = cArray.getJSONObject(j);
					CommentInfo commentInfo = new CommentInfo();
					if (!cJsonObject.isNull("authorname")) {
						commentInfo.authorname = cJsonObject.getString("authorname");
					}
					if (!cJsonObject.isNull("message")) {
						commentInfo.message = cJsonObject.getString("message");
					}
					if (!cJsonObject.isNull("dateline")) {
						commentInfo.dateline = cJsonObject.getString("dateline");
					}
					if (!cJsonObject.isNull("soundurl")) {
						commentInfo.soundurl = cJsonObject.getString("soundurl");
					}
					if (!cJsonObject.isNull("soundtime")) {
						commentInfo.soundtime = cJsonObject.getString("soundtime");
					}
					comments.add(commentInfo);
				}
				model.comments = comments;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Exception---loadComments");
		}
	}
	
	public void toScanActivty() {
		Animation animation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f, Animation.RELATIVE_TO_SELF
				, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		animation.setDuration(400);
		animation.setFillAfter(true);
		animation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				//TODO:跳转
				Intent intent = new Intent();
				intent.putExtra("model", model);
				intent.setClass(mContext, ScanActivity.class);
				startActivity(intent);
				startPullService(false);
				ctrlService(false);
			}
		});
		rlRoot.startAnimation(animation);
	}
	
	
}
